<template>
  <div>
    <!-- <div ref="pdfContainerRef"></div> -->
    <canvas ref="canvasRef" style="display: block"></canvas>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist'

const canvasRef = ref()

const pdfLoader = async () => {
  try {
    GlobalWorkerOptions.workerSrc = '/pdf.worker.mjs'
    // GlobalWorkerOptions.workerSrc =
    //   'https://cdn.jsdelivr.net/npm/pdfjs-dist@5.4.54/build/pdf.worker.mjs'
    const loadingTask = getDocument(
      'https://ywtb.mps.gov.cn/nxzq/nx-ga-external-file/298108ebc82f4a0aa912824cc879dc10.pdf',
    )
    const pdf = await loadingTask.promise
    // pdfDoc.value = pdf //获取pdf文档流
    // pdfPages.value = pdf.numPages //获取pdf文件的页数
    // renderPage(1) //从第几页开始渲染
    console.log(pdf.numPages, '共计页面')
    console.log(loadingTask.docId)

    const firstPage = await pdf.getPage(1)
    const viewport = firstPage.getViewport({
      scale: 1,
    })
    const dpr = window.devicePixelRatio || 1
    console.log(dpr)

    if (canvasRef.value) {
      canvasRef.value!.width = viewport.width * dpr
      canvasRef.value!.height = viewport.height * dpr
      // 根据当前页面大小，设置canvas的缩放
      const scale = document.documentElement.clientWidth / viewport.width
      canvasRef.value!.style.transform = `scale(${scale})`
      canvasRef.value!.style.transformOrigin = 'top left'
    }
    const context = canvasRef.value.getContext('2d')
    if (context) {
      const renderContext = {
        canvasContext: context,
        viewport: viewport,
        canvas: canvasRef.value,
      }
      await firstPage.render(renderContext).promise
    }
  } catch (error) {
    console.log(error)
  }
}

onMounted(async () => {
  pdfLoader()
})
</script>

<style scoped></style>
